package com.guigu.qingcheng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.guigu.qingcheng.pojo.TbSku;
import com.guigu.qingcheng.pojo.TbSpu;
import com.guigu.qingcheng.pojo.vo.Goods;
import com.guigu.qingcheng.service.GoodsServiceFeign;
import com.guigu.qingcheng.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
public class ItemController {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;
    @Autowired
    private TemplateEngine templateEngine;

    String filePath= "c:/item/";

    @ResponseBody
    @RequestMapping("/createPage")
    public void createPage(String id,Model model) throws IOException {
        R dateList = goodsServiceFeign.createPage(id);
        Object data = dateList.getData().get("goods");
        Goods goods = JSON.parseObject(JSON.toJSONString(data), Goods.class);
        if (goods.getSkuList() == null || goods.getSpu() == null) {
            throw new RuntimeException("该商品以下架或者不存在");
        }

        TbSpu spu=goods.getSpu();

        List<TbSku> skuList=goods.getSkuList();

        // 创建一个Map容器

        // 查询商品的一二三级分类
        List<R> category=new ArrayList<>();
        category.add(goodsServiceFeign.detail(spu.getCategory1Id()));
        category.add(goodsServiceFeign.detail(spu.getCategory2Id()));
        category.add(goodsServiceFeign.detail(spu.getCategory3Id()));


        // sku地址列表
        Map<String,String> urlMap=new HashMap<>();
        for (TbSku sku:skuList){
            if ("1".equals(sku.getStatus())) {
                String jsonString = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(jsonString, sku.getId() + ".html");
            }
        }

        for (TbSku sku:skuList){
            Context context=new Context();
            Map<String,Object> map=new HashMap<>();
            map.put("spu",spu);
            map.put("sku",sku);

            if (sku.getImages().length()>0) {
                map.put("skuImages", sku.getImages().split(",")); // spu图片列表
            }
            if (spu.getImages().length()>0) {
                map.put("spuImages", spu.getImages().split(",")); //sku图片列表
            }
            map.put("image",category);
            Map paraItems=JSON.parseObject(spu.getParaItems()); //参数列表
            map.put("paraItems",paraItems);
            Map<String,String> specItems =(Map) JSON.parseObject(sku.getSpec()); // 规格列表
            map.put("specItems",specItems);

            Map<String,List> specMap=(Map)JSON.parseObject(spu.getSpecItems());
            for (String key:specMap.keySet()){
                List<String> list=specMap.get(key);
                List<Map> mapList=new ArrayList<>();
                // 循环规格
                for (String value:list){
                    Map map1=new HashMap();
                    map1.put("option",value); // 规格选项
                    //System.out.println(map1);
                    // 是否和sku的规格相同，就选中
                    if (specItems.get(key).equals(value)){
                        //System.out.println(specItems.get(key));
                        map1.put("checked",true); //是否选中
                    } else {
                        map1.put("checked",false);
                    }
                    Map<String,String> spec=(Map)JSON.parseObject(sku.getSpec()); // 当前sku
                    spec.put(key,value);
                    String jsonString = JSON.toJSONString(spec,SerializerFeature.MapSortField);
                    map1.put("url",urlMap.get(jsonString));
                    mapList.add(map1);// 用新集合替换旧集合
                }
                specMap.put(key,mapList);
            }
            map.put("specMap",specMap);
            // 上下文
            context.setVariables(map);
            //System.out.println(map);
            File dir = new File(filePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            dir.createNewFile();
            File dest = new File(dir, sku.getId() + ".html");
            try{
              PrintWriter writer = new PrintWriter(dest, "UTF-8");
              templateEngine.process("item",context,writer);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping("/priceToRedis")
    public Integer priceToRedis(String id){
        Integer price = goodsServiceFeign.price(id);
        return price;
    }
}
